<template>
  <el-dialog
    v-model="visible"
    title="选择图片"
    width="80%"
    :before-close="handleClose"
    class="image-selector-dialog"
  >
    <div class="image-selector">
      <!-- 搜索和操作栏 -->
      <div class="selector-header">
        <div class="search-container">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索图片..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="header-actions">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            @change="handleUpload"
          >
            <el-button type="primary" :icon="Upload">
              上传新图片
            </el-button>
          </el-upload>
          <el-button @click="refreshList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 图片网格 -->
      <div v-loading="loading" class="image-grid">
        <div
          v-for="image in filteredImages"
          :key="image.filename"
          class="image-item"
          :class="{ selected: selectedImage?.filename === image.filename }"
          @click="selectImage(image)"
        >
          <div class="image-wrapper">
            <img 
              :src="getImageUrl(image.url)" 
              :alt="image.filename"
              :data-original-url="image.url"
              @error="handleImageError"
              @load="handleImageLoad"
            />
            <div class="image-overlay">
              <div class="image-info">
                <p class="image-name">{{ image.filename }}</p>
                <p class="image-size">{{ formatFileSize(image.size) }}</p>
                <p class="image-date">{{ formatDate(image.created) }}</p>
              </div>
              <div class="image-actions">
                <el-button
                  type="primary"
                  size="small"
                  :icon="Check"
                  circle
                  @click.stop="selectAndConfirm(image)"
                  title="选择"
                />
                <el-button
                  type="info"
                  size="small"
                  :icon="View"
                  circle
                  @click.stop="previewImage(image)"
                  title="预览"
                />
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click.stop="deleteImage(image)"
                  title="删除"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredImages.length === 0" class="empty-state">
        <el-empty description="暂无图片">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            @change="handleUpload"
          >
            <el-button type="primary">上传第一张图片</el-button>
          </el-upload>
        </el-empty>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <div class="selected-info">
          <span v-if="selectedImage">
            已选择: {{ selectedImage.filename }}
          </span>
        </div>
        <div class="footer-actions">
          <el-button @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            @click="confirmSelection"
            :disabled="!selectedImage"
          >
            确定选择
          </el-button>
        </div>
      </div>
    </template>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      title="图片预览"
      width="60%"
      append-to-body
    >
      <div class="preview-content">
        <img
          v-if="previewImageData"
          :src="getImageUrl(previewImageData.url)"
          :alt="previewImageData.filename"
          class="preview-image"
        />
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Upload,
  Refresh,
  Check,
  View,
  Delete
} from '@element-plus/icons-vue'
import { getImageList, uploadImage, deleteImage as deleteImageApi, getProxiedImageUrl, getFullImageUrl } from '@/utils/upload'
import { formatFileSize } from '@/utils/format'
import { formatDate } from '@/utils/format'
import type { UploadFile } from '@/types/admin'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'select', image: UploadFile): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const searchKeyword = ref('')
const images = ref<UploadFile[]>([])
const selectedImage = ref<UploadFile | null>(null)
const showPreviewDialog = ref(false)
const previewImageData = ref<UploadFile | null>(null)

// 过滤后的图片列表
const filteredImages = computed(() => {
  if (!searchKeyword.value) return images.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return images.value.filter(image =>
    image.filename.toLowerCase().includes(keyword) ||
    image.originalName.toLowerCase().includes(keyword)
  )
})

// 获取图片URL
const getImageUrl = (url: string) => {
  const processedUrl = getProxiedImageUrl(url)
  console.log('图片URL处理:', { original: url, processed: processedUrl })
  return processedUrl
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.error('图片加载失败:', img.src)
  
  // 尝试使用完整URL
  if (!img.src.startsWith('http')) {
    const fullUrl = getFullImageUrl(img.dataset.originalUrl || img.src)
    console.log('尝试使用完整URL:', fullUrl)
    img.src = fullUrl
  }
}

// 处理图片加载成功
const handleImageLoad = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.log('图片加载成功:', img.src)
}

// 加载图片列表
const loadImages = async () => {
  try {
    loading.value = true
    images.value = await getImageList()
  } catch (error: any) {
    console.error('加载图片列表失败:', error)
    ElMessage.error('加载图片列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 搜索是通过计算属性实现的，这里可以添加防抖等优化
}

// 刷新列表
const refreshList = () => {
  loadImages()
}

// 选择图片
const selectImage = (image: UploadFile) => {
  selectedImage.value = image
}

// 选择并确认
const selectAndConfirm = (image: UploadFile) => {
  selectedImage.value = image
  confirmSelection()
}

// 确认选择
const confirmSelection = () => {
  if (selectedImage.value) {
    // 返回完整URL
    const imageWithFullUrl = {
      ...selectedImage.value,
      url: getFullImageUrl(selectedImage.value.url)
    }
    emit('select', imageWithFullUrl)
    handleClose()
  }
}

// 预览图片
const previewImage = (image: UploadFile) => {
  previewImageData.value = image
  showPreviewDialog.value = true
}

// 删除图片
const deleteImage = async (image: UploadFile) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除图片 "${image.filename}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteImageApi(image.filename)
    ElMessage.success('图片删除成功')
    
    // 从列表中移除
    const index = images.value.findIndex(img => img.filename === image.filename)
    if (index > -1) {
      images.value.splice(index, 1)
    }
    
    // 如果删除的是当前选中的图片，清空选择
    if (selectedImage.value?.filename === image.filename) {
      selectedImage.value = null
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除图片失败')
    }
  }
}

// 上传图片
const handleUpload = async (uploadFile: any) => {
  const file = uploadFile.raw
  if (!file) return

  try {
    const url = await uploadImage(file)
    ElMessage.success('图片上传成功')
    
    // 创建图片对象
    const imageObj: UploadFile = {
      filename: file.name.replace(/\.[^/.]+$/, '') + '-' + Date.now() + file.name.match(/\.[^/.]+$/)?.[0] || '',
      originalName: file.name,
      mimetype: file.type,
      size: file.size,
      url: url,
      path: url,
      created: new Date().toISOString()
    }
    
    // 添加到列表开头
    images.value.unshift(imageObj)
    
    // 自动选择新上传的图片
    selectedImage.value = imageObj
  } catch (error: any) {
    console.error('图片上传失败:', error)
    ElMessage.error(`图片上传失败: ${error.message}`)
  }
}

// 关闭对话框
const handleClose = () => {
  selectedImage.value = null
  searchKeyword.value = ''
  visible.value = false
}

// 监听对话框显示状态
watch(visible, (newVisible) => {
  if (newVisible) {
    loadImages()
  }
})

onMounted(() => {
  if (visible.value) {
    loadImages()
  }
})
</script>

<style scoped>
.image-selector-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.search-container {
  flex: 1;
  max-width: 300px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  min-height: 300px;
}

.image-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-item.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 150px;
  background: #f5f5f5;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.1) 0%,
    rgba(0, 0, 0, 0.3) 50%,
    rgba(0, 0, 0, 0.7) 100%
  );
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-info {
  color: white;
}

.image-name {
  font-size: 14px;
  font-weight: 500;
  margin: 0 0 4px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-size,
.image-date {
  font-size: 12px;
  margin: 0;
  opacity: 0.9;
}

.image-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.preview-content {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 60vh;
  object-fit: contain;
}

/* 响应式 */
@media (max-width: 768px) {
  .selector-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-container {
    max-width: none;
  }
  
  .image-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
  }
  
  .dialog-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .footer-actions {
    justify-content: center;
  }
}
</style> 